package com.example.build_input;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.nfc.Tag;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.provider.SyncStateContract;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.build_input.adapter.StudyAdapter;
import com.example.build_input.entity.Study;
import com.example.build_input.utils.Contant;
import com.example.build_input.utils.FilePath;
import com.tencent.smtt.export.external.TbsCoreSettings;
import com.tencent.smtt.sdk.QbSdk;
import com.tencent.smtt.sdk.ValueCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

import static java.security.AccessController.getContext;

public class MainActivity extends Activity {
    private static String TAG = "MainActivity";

    final List<Study> mList=new ArrayList<>();
    List<Study> data=new ArrayList<>();
    private ListView view;
    private TextView title;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        boolean a= getPermission(this);
        if(a){
            init();
        }
    }


//    @SuppressLint("NewApi")
//    @Override
//    protected void onResume() {
//        mList.clear();
//        getFileData(Contant.sgFiles);
//        super.onResume();
//    }


    @Override
    protected void onStart() {
        super.onStart();
        Log.e(TAG,"==========onStart===============");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        mList.clear();
        getFileData(Contant.sgFiles);
        super.onResume();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e(TAG,"==========onResume===============");
    }



    /**
     * 1.读取指定路径文件
     * 2.封装数据
     * 3.展示数据
     * 4.点击事件调用应用打开文件
     */

    private void init(){
        title=findViewById(R.id.hint);
        view=findViewById(R.id.list_item);
        title.setText(Contant.sg_hint);

        mList.clear();
        //创建文件存放路径
        File dir=new File(Contant.sgFiles);
        if(!dir.exists()){
            dir.mkdirs();
        }

        getFileData(Contant.sgFiles);

    }
    @SuppressLint("NewApi")
    private void getFileData(String path){
        File file= new File(path);
        if (!file.exists()) {
            Log.e(TAG,"文件不存在");
        }else{
            File[] files=file.listFiles();
            if(files.length>0){
                for(File f:files){
                    if(f.isDirectory()){
                        getFileData(f.getAbsolutePath());
                    }else{
                        Study study=new Study(f.getName(), FilePath.getModifiedTime(f),FilePath.FormetFileSize(f.length()),f.getAbsolutePath());
                        mList.add(study);

                    }
                }
            }

        }

        //获取文件信息
        data=mList.stream().sorted(Comparator.comparing(Study::getUpdateTime).reversed()).collect(Collectors.toList());

        view.setAdapter(new StudyAdapter(getApplicationContext(),data));
        view.setEmptyView(title);

        List<Study> finalResultData = data;

        view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

//                try {
//                    Intent intent = new Intent();
//                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                    intent.setAction(Intent.ACTION_VIEW);
//                    //Uri.fromFile(new File()) 会出现乱码
//                    intent.setDataAndType(Uri.parse(Uri.decode(finalResultData.get(position).getUrl())), FilePath.getMIMEType(finalResultData.get(position).getUrl()));
//                     startActivity(intent);
//                    Intent.createChooser(intent, "请选择对应的软件打开该附件！");
//                } catch (ActivityNotFoundException e) {
//                    Toast.makeText(MainActivity.this, "附件打开失败，请下载相关软件！", Toast.LENGTH_SHORT).show();
//                }



                // 在调用TBS初始化、创建WebView之前进行如下配置
                HashMap map = new HashMap();
                map.put(TbsCoreSettings.TBS_SETTINGS_USE_SPEEDY_CLASSLOADER, true);
                map.put(TbsCoreSettings.TBS_SETTINGS_USE_DEXLOADER_SERVICE, true);
                QbSdk.initTbsSettings(map);

                QbSdk.openFileReader(MainActivity.this, finalResultData.get(position).getUrl(), null, new ValueCallback<String>() {
                    @Override
                    public void onReceiveValue(String s) {
//                       Toast.makeText(getApplicationContext(),s,Toast.LENGTH_SHORT).show();
                    }
                });

            }
        });


    }



    //申请权限
    private   boolean getPermission(Activity activity){
        boolean rs=false;
        // 声明一个集合，在后面的代码中用来存储用户拒绝授权的权
        List<String> permissionList = new ArrayList<>();
        String[] permissions = new String[]{
                Manifest.permission.READ_EXTERNAL_STORAGE,//读取内存卡
                Manifest.permission.WRITE_EXTERNAL_STORAGE,//写入内存卡
//                Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS,//允许挂载和反挂载文件系统可移动存储
//                Manifest.permission.READ_PHONE_STATE,//读取手机状态和身份
               /* Manifest.permission.ACCESS_WIFI_STATE,//获取使用Wi-Fi等WLAN无线网络
                Manifest.permission.CHANGE_WIFI_STATE,//允许程序改变Wi-Fi连接状态
                Manifest.permission.ACCESS_NETWORK_STATE,//允许程序访问有关GSM网络信息
                Manifest.permission.CHANGE_NETWORK_STATE,//允许程序改变网络连接状态
                Manifest.permission.INTERNET,//访问网络连接，可能产生GPRS流量
                Manifest.permission.BLUETOOTH,//允许程序连接到已配对的蓝牙设备
                Manifest.permission.CAMERA,//相机
                Manifest.permission.WRITE_SETTINGS,//允许程序读取或写入系统设置*/
        };
        permissionList.clear();
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(activity, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                Log.e(TAG,"权限未允许："+permissions[i]+"....");
                permissionList.add(permissions[i]);
            }
        }
        if (permissionList.isEmpty()) {//未授予的权限为空，表示都授予了
            Log.e(TAG,"已经获取到了所有权限");
            return true;
        } else {//请求权限方法
            String[] spermissions = permissionList.toArray(new String[permissionList.size()]);//将List转为数组
            ActivityCompat.requestPermissions(activity, spermissions, 1);
        }
        return rs;
    }



    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode==1){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                boolean request_rs=true;
                for(int i=0;i<grantResults.length;i++){
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        request_rs=false;
                    }
                }
                if(request_rs){
                    Log.e("软件获取权限结果：","获取软件权限成功");
                    init();
                }else{
                    Toast.makeText(this, "您拒绝了软件应用权限，因此无法使用该软件！", Toast.LENGTH_LONG).show();
                    showDialogTipUserGoToAppSettting();

                }
            }

        }
    }

    /**
     * 提示用户去应用设置界面手动开启权限
     */
    private void showDialogTipUserGoToAppSettting() {
        new AlertDialog.Builder(this)
                .setTitle("存储权限不可用")
                .setMessage("请在-应用设置-权限-中，允许应用使用存储权限来保存用户数据")
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 跳转到应用设置界面
                        goToAppSetting();
                        android.os.Process.killProcess(android.os.Process.myPid());
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        android.os.Process.killProcess(android.os.Process.myPid());
                    }
                }).setCancelable(false).show();
    }

    /**
     * 跳转到当前应用的设置界面
     */
    private void goToAppSetting() {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);
        startActivityForResult(intent, 123);
    }

















}
